package com.vegetable.modules.service.finance;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;

/**
 * 财务数据格式化服务
 *
 * @author Qoder
 */
@Service
public class FinancialDataFormatter {

    private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("#,##0.00");

    /**
     * 格式化财务分析数据为文本消息
     *
     * @param financialData 财务分析数据
     * @return 格式化后的文本
     */
    public String formatFinancialAnalysisData(JSONObject financialData) {
        StringBuilder content = new StringBuilder();
        content.append("【财务分析报告】\n\n");

        // 添加总体分析数据
        JSONObject totalAnalyse = financialData.getJSONObject("totalAnalyse");
        if (totalAnalyse != null) {
            content.append("总体财务情况：\n");
            content.append("销售额：").append(formatCurrency(totalAnalyse.get("sales"))).append("\n");
            content.append("支出：").append(formatCurrency(totalAnalyse.get("expenses"))).append("\n");
            content.append("欠款：").append(formatCurrency(totalAnalyse.get("debt"))).append("\n");
            content.append("未回款：").append(formatCurrency(totalAnalyse.get("noReturn"))).append("\n");
            content.append("账户总余额：").append(formatCurrency(totalAnalyse.get("totalBalance"))).append("\n");
            
            Object updateTime = totalAnalyse.get("balanceUpdateTime");
            if (updateTime != null) {
                content.append("数据更新时间：").append(updateTime.toString()).append("\n");
            }
            content.append("\n");
        }

        // 添加月度数据
        List<List> monthData = (List<List>) financialData.get("monthData");
        if (monthData != null && monthData.size() > 1) {
            content.append("月度财务数据：\n");
            // 表头
            List header = monthData.get(0);
            if (header.size() >= 4) {
                content.append(String.format("%-10s %-12s %-12s %-12s\n", 
                    header.get(0), header.get(1), header.get(2), header.get(3)));
            }
            
            // 数据行
            for (int i = 1; i < monthData.size(); i++) {
                List row = monthData.get(i);
                if (row.size() >= 4) {
                    content.append(String.format("%-10s %-12s %-12s %-12s\n",
                        row.get(0),
                        formatCurrency(row.get(1)),
                        formatCurrency(row.get(2)),
                        formatCurrency(row.get(3))));
                }
            }
        }

        return content.toString();
    }

    /**
     * 格式化财务分析数据为Markdown消息
     *
     * @param financialData 财务分析数据
     * @return 格式化后的Markdown文本
     */
    public String formatFinancialAnalysisMarkdown(JSONObject financialData) {
        StringBuilder content = new StringBuilder();
        content.append("# 📊 财务分析报告\n\n");

        // 添加总体分析数据
        JSONObject totalAnalyse = financialData.getJSONObject("totalAnalyse");
        if (totalAnalyse != null) {
            content.append("## 总体财务情况\n\n");
            content.append("| 项目 | 金额 |\n");
            content.append("|------|------|\n");
            content.append("| 销售额 | ").append(formatCurrency(totalAnalyse.get("sales"))).append(" |\n");
            content.append("| 支出 | ").append(formatCurrency(totalAnalyse.get("expenses"))).append(" |\n");
            content.append("| 欠款 | ").append(formatCurrency(totalAnalyse.get("debt"))).append(" |\n");
            content.append("| 未回款 | ").append(formatCurrency(totalAnalyse.get("noReturn"))).append(" |\n");
            content.append("| 账户总余额 | ").append(formatCurrency(totalAnalyse.get("totalBalance"))).append(" |\n\n");
            
            Object updateTime = totalAnalyse.get("balanceUpdateTime");
            if (updateTime != null) {
                content.append("> 数据更新时间: ").append(updateTime.toString()).append("\n\n");
            }
        }

        // 添加月度数据
        List<List> monthData = (List<List>) financialData.get("monthData");
        if (monthData != null && monthData.size() > 1) {
            content.append("## 月度财务数据\n\n");
            // 表头
            List header = monthData.get(0);
            if (header.size() >= 4) {
                content.append("| ").append(header.get(0)).append(" | ").append(header.get(1)).append(" | ").append(header.get(2)).append(" | ").append(header.get(3)).append(" |\n");
                content.append("|----------|----------|----------|----------|\n");
            }
            
            // 数据行
            for (int i = 1; i < monthData.size(); i++) {
                List row = monthData.get(i);
                if (row.size() >= 4) {
                    content.append("| ").append(row.get(0)).append(" | ")
                            .append(formatCurrency(row.get(1))).append(" | ")
                            .append(formatCurrency(row.get(2))).append(" | ")
                            .append(formatCurrency(row.get(3))).append(" |\n");
                }
            }
        }

        content.append("\n[查看详细图表](https://example.com/financial-analysis.html)\n");
        return content.toString();
    }

    /**
     * 格式化货币数值
     *
     * @param value 数值
     * @return 格式化后的货币字符串
     */
    public String formatCurrency(Object value) {
        if (value == null) {
            return "0.00";
        }
        
        try {
            BigDecimal decimal;
            if (value instanceof BigDecimal) {
                decimal = (BigDecimal) value;
            } else {
                decimal = new BigDecimal(value.toString());
            }
            return "¥" + DECIMAL_FORMAT.format(decimal);
        } catch (NumberFormatException e) {
            return value.toString();
        }
    }

    /**
     * 格式化财务摘要信息
     *
     * @param financialData 财务数据
     * @return 格式化后的摘要信息
     */
    public String formatFinancialSummary(JSONObject financialData) {
        StringBuilder summary = new StringBuilder();
        
        // 添加总体分析数据
        JSONObject totalAnalyse = financialData.getJSONObject("totalAnalyse");
        if (totalAnalyse != null) {
            summary.append("总体情况：\n");
            summary.append("- 销售额：").append(formatCurrency(totalAnalyse.get("sales"))).append("\n");
            summary.append("- 支出：").append(formatCurrency(totalAnalyse.get("expenses"))).append("\n");
            summary.append("- 账户总余额：").append(formatCurrency(totalAnalyse.get("totalBalance"))).append("\n");
            summary.append("- 欠款：").append(formatCurrency(totalAnalyse.get("debt"))).append("\n");
            summary.append("- 未回款：").append(formatCurrency(totalAnalyse.get("noReturn"))).append("\n\n");
        }
        
        return summary.toString();
    }
}